package com.example.demo.thread.util;


import java.io.Closeable;
import java.io.IOException;
import java.util.Random;
import java.util.logging.Logger;

/**
 * @author: htc 《Java多线程编程实战指南（核心篇）》
 * @date: Created in 11:20 2019/1/8.
 */
public class Tools {
    private static final Random rnd = new Random();
    private static final Logger log = Logger.getAnonymousLogger();

    public static void startAndWaitTerminated(Thread... threads) throws InterruptedException {
        if (null == threads) {
            throw new IllegalArgumentException("threads is null !");
        }
        for (Thread t : threads) {
            t.start();
        }
        for (Thread t : threads) {
            t.join();
        }
    }

    public static void startThread(Thread... threads) {
        if (null == threads) {
            throw new IllegalArgumentException("threads is null !");
        }
        for (Thread t : threads) {
            t.start();
        }
    }

    public static void silentClose(Closeable... cloneable) {
        if (null == cloneable) {
            return;
        }
        for (Closeable c : cloneable) {
            if (null == c) {
                continue;
            }
            try {
                c.close();
            } catch (IOException e) {
            }
        }
    }

    public static void randomPause(int maxPauseTime) {
        int sleepTime = rnd.nextInt(maxPauseTime);
        try {
            Thread.sleep(sleepTime);
        } catch (InterruptedException e) {
            Thread.currentThread().interrupt();
        }
    }

    public static void randomPause(int maxPauseTime, int minPauseTime) {
        int sleepTime = maxPauseTime == minPauseTime ? minPauseTime : rnd.nextInt(maxPauseTime - minPauseTime) + minPauseTime;
        try {
            Thread.sleep(sleepTime);
        } catch (InterruptedException e) {
            Thread.currentThread().interrupt();
        }
    }
}
